<template>
  <div v-if="loginPanle" class="login">
    <div class="logon-content">
      <!-- 配置logo -->
      <img
        v-if="loginPanle && loginPanle.logoPath!==''"
        :src="loginPanle.logoPath"
        class="logo"
      >
      <!-- 默认logo -->
      <img
        v-else
        src="../../assets/logo.png"
        class="logo"
      >
    </div>
    <div class="content">
      <div class="user-info-username">
        <i class="jeicon jeicon-user-o" />
        <input
          ref="inputBlurName"
          v-model="loginPanle.loginInfo.phone"
          type="text"
          placeholder="手机号/账户"
          class="form-input"
        >
        <span
          v-show="hasLoginHistory"
          @tap="loginHistory(false)"
          class="user-list-span"
        >
          <i class="jeicon jeicon-angle-right user-list" />
        </span>
      </div>
      <div
        v-show="loginPanle.loginState"
        class="user-info-pwd"
      >
        <i class="jeicon jeicon-lock" />
        <input
          ref="inputBlurPassword"
          v-model="loginPanle.loginInfo.pwd"
          :type="loginPanle.showPwd ? 'password' : 'text'"
          @keyup.enter="login"
          placeholder="密码"
          class="form-input"
          maxlength="20"
        >
        <i
          :class="['jeicon','viewpwd',{
            'jeicon-eye': loginPanle.showPwd,
            'jeicon-eye-close': !loginPanle.showPwd
          }]"
          @tap="loginPanle.showPwd=!loginPanle.showPwd"
          class="jeicon viewpwd"
        />
      </div>
      <div
        v-show="!loginPanle.loginState"
        class="user-info-pwd-message"
      >
        <i class="jeicon jeicon-lock " />
        <input
          v-model="loginPanle.loginInfo.validateCode"
          type="number"
          placeholder="短信动态密码"
          class="form-input"
          oninput="if(value.length>6)value=value.slice(0,6)"
          maxlength="6"
          pattern="\d*"
        >
        <button
          @tap="getValidateCode"
          class="get-validate-code"
        >
          <span v-show="sendAuthCode">获取</span>
          <span v-show="!sendAuthCode">{{ auth_time }}s</span>
        </button>
      </div>
      <div class="pwd">
        <label
          v-show="loginPanle.loginState"
        ><input
          v-model="loginPanle.remberStatus"
          type="checkbox"
          style="vertical-align:middle"
        ><span style="vertical-align:middle;">记住密码</span></label>
        <label
          v-show="loginPanle.loginState"
          @tap="loginPanle.stateLogin()"
        >动态密码登录</label>
        <label
          v-show="!loginPanle.loginState"
          @tap="loginPanle.passworldLogin()"
        >个人密码登录</label>
        <label @tap="forgetPwd">忘记密码？</label>
      </div>
      <button
        ref="loginBtn"
        @tap="login"
        data-loading-text="登录中..."
        class="login-btn mui-btn "
      >
        登录
      </button>
      <!-- IOS上架 -->
      <!-- <span
        class="register-btn">
        <span @tap="register">立即注册</span>
      </span> -->
    </div>
    <sel-company-list
      ref="selCompanList"
      :company-list="loginPanle.companyList"
      :state="loginPanle.loginState"
      :show-modal-flag="loginPanle.showModalFlag"
      :user-info="loginPanle.loginInfo"
      :app-login="appLoginInfo"
      @showFlag="showFlag"
      type="loginPage"
    >
      <div slot="modalTitle">
        选择企业
      </div>
    </sel-company-list>
  </div>
</template>

<script type="text/ecmascript-6">
import { validate, toastValidate } from '../../../../util/validate';
import { fetchSendValidateCode } from '../../actions/login';
import selCompanyList from '../../components/selcompanyList/index';
import AppLogin from '../../class/appLogin'
export default {
  name: 'Login',
  components: {
    'sel-company-list': selCompanyList,
  },
  data() {
    return {
      loginPanle: new AppLogin({vm: this}),
      appLoginInfo: {},
      sendAuthCode: true,
      auth_time: 0,
    };
  },
  computed: {
    hasLoginHistory() {
      let loginHistory = [];
      if (JE.getLSItem('loginHistory')) {
        loginHistory = JSON.parse(JE.getLSItem('loginHistory')) || [];
      }
      return loginHistory.length > 0;
    },
  },
  created() {
    // 首页返回键处理
    // 处理逻辑：1秒内，连续两次按返回键，则退出应用；
    let first = null;
    // const oldBack = mui.back;
    mui.back = function back() {
      // 首次按键，提示‘再按一次退出应用’
      if (!first) {
        first = new Date().getTime();
        mui.toast('再按一次退出应用');
        setTimeout(() => {
          first = null;
        }, 1000);
      } else if (new Date().getTime() - first < 1000) {
        plus.runtime.quit();
      }
    };
    Waves.init();
    // this.initUserPrivacy();
  },
  mounted() {
    // this.loginHistory(true);
  },
  methods: {
        /**
     * @description:
     * APP弹框用户隐私说明
     * 用户同意存储标识
     * 用户不同意关闭app
     * @param :
     * @return {*}
     */
    initUserPrivacy() {
      const openConfirm =JE.getLSItem('user_privacy')!="1"
      // 用户协议地址
      const userUrl=JE.getLSItem('userUrl')||'https://www.china-hbp.com/%E9%9A%90%E7%A7%81%E7%AD%96%E7%95%A5.txt'
      // 隐私协议地址
      const privacyUrl=JE.getLSItem('privacyUrl')||'https://www.china-hbp.com/%E9%9A%90%E7%A7%81%E7%AD%96%E7%95%A5.txt'
      openConfirm && window.plus && mui.os.android && mui.confirm(
        `请您务必审慎阅读，理解“服务协议”和“隐私协议”的各条款。您可点击<span style="color:blue" onclick="plus.runtime.openURL('${userUrl}')" >《用户协议》</span>和<span   style="color:blue"onclick="plus.runtime.openURL('${privacyUrl}')" >《隐私协议》</span>
了解详情。如您同意，请点击“同意”开始接收我们的服务。`,
        "用户声明和隐私声明",
        ["暂不同意", "同意"],
        function (e) {
          if (e.index == 0) {
            plus.runtime.quit();
          } else {
            JE.setLSItem("user_privacy", "1");
          }
        },
        "div"
      );
    },
    // 展示公司列表
    showFlag() {
      this.loginPanle.showModalFlag = false;
      let timer = setTimeout(() => {
        this.loginPanle.btnReset();
      }, 10);
      timer = null;
    },
    // 登录记录，只获取前五
    loginHistory(init) {
      return;
      let loginHistory = [];
      const buttons = [];
      if (JE.getLSItem('loginHistory')) {
        loginHistory = JSON.parse(JE.getLSItem('loginHistory')) || [];
      }
      if (loginHistory.length > 5) {
        loginHistory = loginHistory.slice(0, 6);
      }
      for (let i = 0; i < loginHistory.length; i += 1) {
        buttons.push({ title: loginHistory[i] });
      }
      if (init) {
        this.$set(this.loginInfo, 'phone', loginHistory[0]);
      }
      // 翟梓钦注释
      // plus.nativeUI.actionSheet({
      //   title: '请选择',
      //   cancel: '取消',
      //   buttons
      // }, (e) => {
      //   if (e.index > 0) {
      //     this.$set(this.loginInfo, 'phone', buttons[e.index - 1].title);
      //   }
      // });
    },
    // 登录
    async login() {
      // 页面失去焦点
      mui('.mui-btn')
        .button('loading');
      Waves.attach('.login-btn', ['waves-button', 'waves-float']);
      if (!toastValidate('手机号', validate.isNull(this.loginPanle.loginInfo.phone))
          || (this.loginPanle.loginState && !toastValidate('密码', validate.isNull(this.loginPanle.loginInfo.pwd)))
          || (!this.loginPanle.loginState && !toastValidate('短信动态验证码', validate.isNull(this.loginPanle.loginInfo.validateCode)))) {
        mui('.mui-btn')
          .button('reset');
        return false;
      }
      this.loginPanle.sendLogin();
    },
    // 获取验证码
    async getValidateCode() {
      if (
        !toastValidate('手机号/账户', validate.isNull(this.loginPanle.loginInfo.phone))
          || !toastValidate('', validate.isPhone(this.loginPanle.loginInfo.phone), '手机号格式不正确')
      ) {
        return false;
      }

      if (this.sendAuthCode) {
        const res = await fetchSendValidateCode({
          email: this.loginPanle.loginInfo.phone,
          type: 'PHONE',
          cz: 'LOGIN',
        });
        mui.toast(res.message);
        if (res.success) {
          this.sendAuthCode = false;
          this.auth_time = 59;
          const auth_timetimer = setInterval(() => {
            this.auth_time--;
            if (this.auth_time <= 0) {
              this.sendAuthCode = true;
              clearInterval(auth_timetimer);
            }
          }, 1000);
        }
      }
    },
    // 忘记密码
    forgetPwd() {
      this.$router.push({
        path: '/JE-PLUGIN-LOGIN/forget_pwd',
      });
    },
    // 注册
    register() {
      this.$router.push({
        path: '/JE-PLUGIN-LOGIN/register_login',
      });
    },
  },
};
</script>
<style>
  .mui-btn .mui-spinner {
    width: 40px !important;
    height: 40px !important;
  }

  .mui-toast-container1 {
    bottom: 50px !important;
  }
</style>
<style lang="less" scoped>
@import "./style/index.less";
</style>
